﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnsQ.infoViewModel;
using AnsQ.Models;
using AnsQ.Helper;
using System.Data;

namespace AnsQ.Controllers
{
    /// <summary>
    /// This Controller is for Users not Admin
    /// </summary>
    public class AuthController : Controller
    {
        // GET: Auth
        public JsonResult SetToken(string UserName, string pwd)
        {
            string Gid = Guid.NewGuid().ToString();
            DataResult result = new DataResult();

            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(pwd))
            {
                if (CheckUser(UserName, pwd))
                {
                    AnsGameEntities db = new AnsGameEntities();
                    string UID = db.AUser.Where(a => a.PlayName == UserName.Trim()).Select(c => c.ID).FirstOrDefault();
                    string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                    var payload = new Dictionary<string, object>
                {
                    { "PlayName",UserName },
                    { "ID", Gid },
                    { "time",time}
                };
                    result.Token = JWT.JwtHelp.SetJwtEncode(payload);
                    result.Success = true;
                    result.Message = "成功";

                    //保存生成的Token
                    SaveInDB(result.Token, UID, Gid);
                }
                else
                {
                    result.Token = "";
                    result.Success = false;
                    result.Message = "生成token失败";
                }
            }
            else
            {
                result.Token = "";
                result.Success = false;
                result.Message = "用户名或密码不合法";
            }
            return Json(result);
        }

        /// <summary>
        /// 验证用户是否合法
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        private bool CheckUser(string UserName, string pwd)
        {
            Boolean isOK = false;
            DataTable usertable = TSQLHelper.GetDataTableBySQL("select * from AUser where PlayName=@pname and Password=@pwd", new string[] { "@pname", "@pwd" }, new string[] { UserName.Trim(), pwd.Trim() });

            if (usertable.Rows.Count > 0 && usertable.Rows.Count < 2)
            {
                isOK = true;
            }

            return isOK;
        }

        private void SaveInDB(string Token, string UID,string guid)
        {
            string Gid = Guid.NewGuid().ToString();
            string UpdateTime = DateTime.Now.ToString();
            Helper.TSQLHelper.DoRemove("delete from TokenList where UID=@uid", new string[] { "@uid" }, new string[] { UID });
            Helper.TSQLHelper.InsertOrUpdateSQL("insert into TokenList values(@gid,@TokenGuid,@token,@uid,@UpdateTime)", new string[] { "@gid", "TokenGuid", "@token", "@uid", "@UpdateTime" }, new string[] { Gid, guid, Token, UID, UpdateTime });
        }

        
    }
}